using UnityEngine;

public class VectorConverter : Newtonsoft.Json.JsonConverter
{
    public override bool CanConvert(System.Type objectType)
    {
        return objectType == typeof(UnityEngine.Vector3);
    }

    public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
    {
        if (reader.TokenType == Newtonsoft.Json.JsonToken.Null)
        {
            return Vector3.zero;
        }
        
        try
        {
            // 创建一个临时对象来读取JSON属性
            var tempObj = serializer.Deserialize<Newtonsoft.Json.Linq.JObject>(reader);
            if (tempObj == null)
            {
                return Vector3.zero;
            }
            
            float x = tempObj.ContainsKey("x") ? tempObj["x"].ToObject<float>() : 0f;
            float y = tempObj.ContainsKey("y") ? tempObj["y"].ToObject<float>() : 0f;
            float z = tempObj.ContainsKey("z") ? tempObj["z"].ToObject<float>() : 0f;
            
            return new Vector3(x, y, z);
        }
        catch
        {
            Debug.LogWarning("Vector3反序列化失败，返回零向量");
            return Vector3.zero;
        }
    }

    public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
    {
        if (value == null)
        {
            writer.WriteNull();
            return;
        }
        
        if (value is UnityEngine.Vector3 vector3)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("x");
            writer.WriteValue(System.Math.Round(vector3.x, 5));
            writer.WritePropertyName("y");
            writer.WriteValue(System.Math.Round(vector3.y, 5));
            writer.WritePropertyName("z");
            writer.WriteValue(System.Math.Round(vector3.z, 5));
            writer.WriteEndObject();
        }
        else
        {
            writer.WriteNull();
        }
    }
}